package gw.com.android.presenter.http;

import android.text.TextUtils;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import gw.com.android.app.AppMain;
import gw.com.android.model.ConfigUtil;
import gw.com.android.utils.CacheUtils;
import okhttp3.Request;
import okhttp3.Response;
import www.com.library.app.Logger;
import www.com.library.interfaces.ReqCallBack;

/**
 * 交易风向标的请求
 *
 * @author hank
 * @since 2018-8-2
 */
public class HomeGainListRequest {

    private String cacheFileName = "_gain_list.dat";

    public HomeGainListData fetchLocal() {
        String str = CacheUtils.readFile(cacheFileName);
        return parse(str, false);
    }

    public void call(final ReqCallBack<HomeGainListData> callBack) {
        String mUrl = ConfigUtil.instance().getUrlPath("gainList");
        new Https(mUrl).responseOnUiThread(false).get(new Https.ResponseCallback<String>() {
            @Override
            public void onSuccess(Request request, Response response, String result, int code) {
                HomeGainListData data = parse(result, true);
                postSuccess(data, callBack);
            }

            @Override
            public void onFailure(Request request, IOException e) {
                postFailure(e, callBack);
            }
        });
    }

    private void postSuccess(final HomeGainListData data, final ReqCallBack<HomeGainListData> callBack) {
        AppMain.getApp().getHandler().post(new Runnable() {
            @Override
            public void run() {
                callBack.onReqSuccess(data);
            }
        });
    }

    private void postFailure(Exception e, final ReqCallBack<HomeGainListData> callBack) {
        final String msg = e == null ? "" : e.getMessage();
        AppMain.getApp().getHandler().post(new Runnable() {
            @Override
            public void run() {
                callBack.onReqFailed(msg);
            }
        });
    }

    private void storeLocal(String str) {
        CacheUtils.writeFile(cacheFileName, str);
    }

    private HomeGainListData parse(String str, boolean cache) {
        Log.d("HomeGainListData", "" + str);
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        try {
            JSONObject jsonObject = new JSONObject(str);
            JSONObject dataJson = jsonObject.optJSONObject("data");
            if (dataJson != null) {
                HomeGainListData data = new HomeGainListData();
                data.gainSingleListData = new ArrayList<>();
                //先解析单笔最高盈利
                if (dataJson.has("highest")) {
                    JSONArray highest = dataJson.optJSONArray("highest");

                    GainSingleList temp;
                    for (int i = 0; i < highest.length(); i++) {
                        temp = new GainSingleList();
                        temp.highest_profit = highest.getJSONObject(i).optDouble("highest_profit");
                        temp.symbol = highest.getJSONObject(i).optString("symbol");
                        temp.open_date = highest.getJSONObject(i).optString("open_date");
                        temp.close_date = highest.getJSONObject(i).optString("close_date");
                        data.gainSingleListData.add(temp);
                    }
                }

                data.gainListData = new ArrayList<>();
                //再解析盈利榜
                if (dataJson.has("GTS2")) {
                    JSONArray GTS2 = dataJson.optJSONArray("GTS2");
                    GainList temp2;
                    for (int i = 0; i < GTS2.length(); i++) {
                        temp2 = new GainList();
                        temp2.login = GTS2.getJSONObject(i).optString("login");
                        temp2.profit = GTS2.getJSONObject(i).optDouble("profit");
                        temp2.yield = GTS2.getJSONObject(i).optString("yield");//19.11%
                        temp2.trade_winning = GTS2.getJSONObject(i).optString("trade_winning");//100.00%
                        temp2.release_date = GTS2.getJSONObject(i).optString("release_date");//100.00%
                        data.gainListData.add(temp2);
                    }
                }
                if (cache) {
                    storeLocal(str);
                }
                return data;
            }
        } catch (JSONException e) {
            Logger.e(e);
        }
        return null;
    }

    public class HomeGainListData {
        public List<GainList> gainListData;
        public List<GainSingleList> gainSingleListData;
    }

    public class GainList {
        /*
         * 盈利榜
         */
        public String login;//账户
        public double profit;//当日盈亏
        public String yield;//当日收益率
        public String trade_winning;//当日胜率
        public String release_date;//更新时间
    }

    public class GainSingleList {
        /*
         * 单笔最高盈利
         */
        public double highest_profit;//盈利额
        public String symbol;//交易产品
        public String open_date;//开仓日期
        public String close_date;//平仓日期
    }
}
